package com.wlz.jvm;

import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 *  自定义类加载
 *
 *   自定义类加载器只需要继承 java.lang.ClassLoader 类，该类有两个核心方法，一个是 loadClass(String, boolean)，
 *   实现了双亲委派机制，还有一个方法是findClass，默认实现是空 方法，所以我们自定义类加载器主要是重写findClass方法。
 */
public class MyClassLoader1 extends ClassLoader {

    private String classPath;

    public MyClassLoader1(String classPath) {
        this.classPath = classPath;
    }

    private byte[] loadByte(String name) throws Exception {
        name = name.replaceAll("\\.", "/");
        FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
        int len = fis.available();
        byte[] data = new byte[len];
        fis.read(data);
        fis.close();

        return data;
    }

    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] bytes = loadByte(name);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException();
        }

    }

    /**
     * 重写loadclass 方法打破双亲委派
     * @param name
     * @param resolve
     * @return
     * @throws ClassNotFoundException
     */
    protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();



                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();
                    c = findClass(name);
                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();

            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }




    public static void main(String[] args) throws Exception {

        MyClassLoader1 classLoader = new MyClassLoader1("/Users/wlz/Desktop/test");

        Class clazz = classLoader.loadClass("java.lang.String");

        Object object = clazz.newInstance();

        Method method = clazz.getDeclaredMethod("sout",null);

        method.invoke(object,null);

        System.out.println(clazz.getClassLoader().getClass().getName());

    }
}
